#include "MultiThread.h"
#include "ThreadManager.h"
#include "ThreadTask.h"

CThreadManager::CThreadManager()
{
	int32 mAllThreadNum = FPlatformMisc::NumberOfWorkerThreadsToSpawn();
	Create();
}

CThreadManager::CThreadManager(int32 threadNum)
{
	mAllThreadNum = threadNum;
	Create();
}

CThreadManager::~CThreadManager()
{
	Destroy();
}

void CThreadManager::Create()
{
	mThreadPool = FQueuedThreadPool::Allocate();

	if (mThreadPool == nullptr)
	{
		UE_LOG(LogClass, Warning, TEXT("thread pool create failure"));
		return;
	}
	verify(mThreadPool->Create(mAllThreadNum));
}

void CThreadManager::Destroy()
{
	if (mThreadPool != nullptr)
	{
		UE_LOG(LogClass, Log, TEXT("call mThreadPool->Destroy()"));
		mThreadPool->Destroy();
	}
	else
	{
		UE_LOG(LogClass, Warning, TEXT("mThreadPool duplicate Destroy"));
		return;
	}

	if (mThreadPool != nullptr)
	{
		UE_LOG(LogClass, Log, TEXT("delete mThreadPool"));
		delete mThreadPool;
		mThreadPool = nullptr;
	}
}

void CThreadManager::RunBackground(std::function<void(void)> func)
{
	if (mThreadPool == nullptr)
	{
		UE_LOG(LogClass, Warning, TEXT("mThreadPool not be created"));
		return;
	}
	CThreadTask *task = new CThreadTask(mThreadPool);
	task->StartBackgroundTask(func);
}

void CThreadManager::RunSync(std::function<void(void)> func)
{
	if (mThreadPool == nullptr)
	{
		UE_LOG(LogClass, Warning, TEXT("mThreadPool not be created"));
		return;
	}
	CThreadTask *task = new CThreadTask(mThreadPool);
	task->StartSyncTask(func);
}
